package com.csthink.common.infrastructure.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;

import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;

/**
 * system config cache on jvm level
 *
 * @author <a href="mailto:security.2009@live.cn">Mars</a>
 * @since 2023-09-11
 */
@Slf4j
public class SystemConfigLocalCacheUtils {

    private static ConcurrentHashMap<String, String> HOT_KEYS = new ConcurrentHashMap<>();

    private static final ConcurrentHashMap<String, String> LOCAL_CACHE = new ConcurrentHashMap<>();

    public static String getCache(String key) {
        if (StringUtils.isBlank(key)) {
            log.warn("key is null or blank!");
            return null;
        }
        return LOCAL_CACHE.get(key);
    }

    public static String putCache(String key, String value) {
        if (StringUtils.isBlank(key) || value == null) {
            log.error("key is null/blank or value is blank!");
            return null;
        }
        log.info("set system config localCache, key={},value={E}", key, value);
        return LOCAL_CACHE.put(key, value);
    }

    public static boolean existCache(String key) {
        if (StringUtils.isBlank(key)) {
            log.warn("key is null or blank!");
            return false;
        }
        return LOCAL_CACHE.containsKey(key);
    }

    public static String removeCache(String key) {
        log.info("hotkey - remove cache: {}", key);
        if (StringUtils.isBlank(key)) {
            log.warn("key is null or blank!");
            return null;
        }
        return LOCAL_CACHE.remove(key);
    }

    public static void flushAllCache() {
        LOCAL_CACHE.clear();
        log.info("flush all system config local cache");
    }

    public static void putHotKeys(String[] hotKeys) {
        if (hotKeys == null || hotKeys.length < 1) {
            return;
        }
        for (String hotKey : hotKeys) {
            if (StringUtils.isNotBlank(hotKey)) {
                HOT_KEYS.put(hotKey, Strings.EMPTY);
            }
        }
        log.info("put hotkeys: {}", Arrays.toString(hotKeys));
    }

    public static boolean isHotKey(String key) {
        if (StringUtils.isBlank(key)) {
            return false;
        }
        return HOT_KEYS.containsKey(key);
    }

    public static void flushKey() {
        HOT_KEYS.clear();
        log.info("flush all system config key!");
    }
}
